#include <iostream>
#include <zmq.h>
#include <chrono>
#include "test_zero_mq.pb.h"

using namespace std::chrono_literals;

int main() {
    void* context = zmq_ctx_new();
    void* socket = zmq_socket(context, ZMQ_REQ);
    zmq_connect(socket, "tcp://101.35.44.80:5555");

    double max = 0.0;
    int i = 0;
    while (i++ < 10000)
    {
        auto st = std::chrono::system_clock::now();
        messages::Request request;
        request.set_data("World!");

        std::string serialized_request;
        request.SerializeToString(&serialized_request);
        
        zmq_msg_t zmq_request;
        zmq_msg_init_size(&zmq_request, serialized_request.size());
        memcpy(zmq_msg_data(&zmq_request), serialized_request.data(), serialized_request.size());
        zmq_msg_send(&zmq_request, socket, 0);

        zmq_msg_t zmq_response;
        zmq_msg_init(&zmq_response);
        zmq_msg_recv(&zmq_response, socket, 0);

        messages::Response response;
        response.ParseFromArray(zmq_msg_data(&zmq_response), zmq_msg_size(&zmq_response));

        // std::cout << "Received response: " << response.result() << std::endl;
        zmq_msg_close(&zmq_request);
        zmq_msg_close(&zmq_response);

        auto ed = std::chrono::system_clock::now();
        auto dur = std::chrono::duration<double, std::micro>(ed - st).count();
        // std::cout << "time usage: " << dur << "us\n";

        if (__glibc_unlikely(max < dur))
        {
            max = dur;
        }
    }

    std::cout << "max time is : " << max << "ms\n";

    zmq_close(socket);
    zmq_ctx_destroy(context);

    return 0;
}
